package framework.handler;

import lombok.extern.slf4j.Slf4j;
import framework.provier.ServiceProvider;
import framework.transport.codec.XRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Component
public class XRequestHandler {

    @Autowired
    private ServiceProvider serviceProvider;


    public Object handle(XRequest xRequest) {
        Object service = serviceProvider.getService(xRequest.getRpcServiceName());
        if (service == null) {
            throw new RuntimeException("获取不到服务 " + xRequest.getRpcServiceName());
        }
        return invoke(xRequest, service);
    }

    private Object invoke(XRequest xRequest, Object service) {

        Object result;
        try {
            Method method = service.getClass().getMethod(xRequest.getMethodName(), xRequest.getParamTypes());
            result = method.invoke(service, xRequest.getParameters());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

}
